package Veterinaria.servlets;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import Veterinaria.excepcion.CodigoDuplicadoExcepcion;
import Veterinaria.excepcion.DAOExcepcion;
import Veterinaria.excepcion.ValidaApellidoExcepcion;
import Veterinaria.excepcion.ValidaNombreExcepcion;
import Veterinaria.modelo.Dueno;
import Veterinaria.negocio.GestionPersona;


/**
 * Servlet implementation class DuenoServlet
 */
@WebServlet("/DuenoServlet")
public class DuenoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DuenoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		System.out.println("Entro");
		PrintWriter out = response.getWriter();
	    response.setContentType("text/html");
	    response.setHeader("Cache-control", "no-cache, no-store");
	    response.setHeader("Pragma", "no-cache");
	    response.setHeader("Expires", "-1");
	    
	    System.out.println("Servlets");
	    JSONArray arrayObj = new JSONArray();
	    JSONObject obj1 = new JSONObject();
	    System.out.println("Servlets1");
	    	
		GestionPersona dueno = new GestionPersona();
		String nom = null;
		try {
			System.out.println("Servlets2");
			String query = request.getParameter("term");
	        System.out.println(query);
	        query = query.toLowerCase();
	        
			Collection<Dueno> duenos = dueno.ListaDuenoXNombre(query);

			for (Dueno due : duenos) {
				if (due.getApellido_persona().toLowerCase().startsWith(query))
					nom = due.getApellido_persona() + " " + due.getNombre_persona();
				obj1.put("label", nom);
				obj1.put("value", nom);
				obj1.put("id", due.getCodigo_persona());
				obj1.put("nom", due.getNombre_persona());
				obj1.put("ape", due.getApellido_persona());
				obj1.put("tipo", due.getTipo_persona());
				obj1.put("email", due.getEmail_persona());
				obj1.put("direc", due.getDireccion());
				obj1.put("telf", due.getTelefono_fijo());
				obj1.put("cel", due.getTelefono_celular());
				obj1.put("sex", due.getSexo());
				obj1.put("ruc", due.getRuc());
				obj1.put("imagen", due.getImagen());
				obj1.put("not", due.getNotas());
				arrayObj.add(obj1.toString());
				obj1.clear();
			}

		} catch (DAOExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
	        out.println(arrayObj);
	        out.close();
		}	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//	
		GestionPersona per = new GestionPersona();
		
		Map<String,String> parameterMap = new HashMap<String,String>();
		//String x = request.getParameter("txtAccion");
		File pathUpload = null;
		String x = null;
		String ruta = null;
		try {
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);

			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(2000);
			ServletFileUpload fu = new ServletFileUpload(factory);

			java.util.List lista = fu.parseRequest(request);

			for (FileItem item : items) {
				if (item != null) {
					if (item.isFormField()) {
						// Process regular form field (input
						// type="text|radio|checkbox|etc", select, etc).
						//String fieldname = item.getFieldName();
						//String fieldvalue = item.getString();
						parameterMap.put(item.getFieldName(), item.getString());
						System.out.println("form field");
						// ... (do your job here)
					} else {
						// Process form file field (input type="file").
						String fieldname = item.getFieldName();
						String filename = FilenameUtils.getName(item.getName());
						InputStream filecontent = item.getInputStream();
						// ... (do your job here)
						String contentType = item.getContentType();
						x = parameterMap.get("txtcondicion");
						if (x.equals("INSERTAR")){
						Dueno codigo = null;
						try {
							codigo = per.GenerarCodigo();
						} catch (DAOExcepcion e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						
						File directorio = new File(getServletContext().getContextPath());
								//.getRealPath("/"));
						pathUpload = new File("D:/UPC/Programas/eclipse_indigo_64_svn_android/Workspace/ThunderBolt/WebContent/img_pet" + "/"
								+ codigo.getCodigo_persona() + ".jpg");
						
						ruta = "img_pet/" + codigo.getCodigo_persona() + ".jpg";
						
						
						item.write(pathUpload);
						System.out.println("Upload; ruta: " + pathUpload);
						}		
					}
				}

			}
		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		String  nombre = parameterMap.get("NomDueno");
		String  apellido = parameterMap.get("apellido");
		String  tipopersona = parameterMap.get("tipopersona");
		String  email = parameterMap.get("email");
		String  direccion = parameterMap.get("direccion");
		String  telefono = parameterMap.get("telefono");
		String  celular = parameterMap.get("celular");
		String  sexodueno = parameterMap.get("sexodueno");
		String  ruc = parameterMap.get("ruc");
		String  notas = parameterMap.get("notas");
		String  imagen = ruta;
		String  txtIddueno = parameterMap.get("txtIddueno");
		
   if (x.equals("INSERTAR")){		

		Dueno codigo = null;
		try {
			codigo = per.GenerarCodigo();
		} catch (DAOExcepcion e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	
		try {
			per.insertaDueno(codigo.getCodigo_persona(), nombre, apellido, tipopersona, email, direccion, telefono, celular, ruc, sexodueno, "1", codigo.getCodigo_persona(), imagen, notas);
			System.out.println("inserto en dueno");
		} catch (DAOExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CodigoDuplicadoExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ValidaNombreExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ValidaApellidoExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestDispatcher  rd= request.getRequestDispatcher("dueno.jsp");
		rd.forward(request, response);

	}else if (x.equals("MODIFICAR")){

		try {
			per.actualizarDueno(txtIddueno, nombre, apellido, tipopersona, email, direccion, telefono, celular, ruc, sexodueno, "1", txtIddueno, imagen, notas);

		} catch (DAOExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestDispatcher  rd= request.getRequestDispatcher("modificar_dueno.jsp");
		rd.forward(request, response);
	}else if (x.equals("ELIMINAR")){

//		String  txtIddueno = ;
//		System.out.println(txtIddueno);

		try {
			
//			String Eliminarregistro=request.getParameter("txtIddueno");
			
			
			per.EliminarDueno(txtIddueno);

		} catch (DAOExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestDispatcher  rd= request.getRequestDispatcher("eliminar_dueno.jsp");
		rd.forward(request, response);
		
	}
   
	}

}
